#!/usr/bin/env python
# -*- coding:utf-8 -*-
# 项目名称:bysms
# 文件名 :customer.py
# @Time :2024/4/17 11:13
# @Author :wangyong
'''
简介:

'''
from django.http import JsonResponse
import json

from common.models import Customer


def dispatcher(request):
    #将请求参数统一放入request的params属性中,方便后续处理
    #get请求参数在request对象的get属性中
    if request.method=="GET":
        request.params=request.Get
    #post/put/delete 请求参数从request对象的body属性中获取
    elif request.method in ['POST','PUT','DELETE']:
        request.params=json.loads(request.body)

    #根据不同的action分派给不同的函数进行处理
    action=request.params['action']
    if action=='list_customer':
        return listcustomers(request)
    elif action=='add_customer':
        return addcustomer(request)
    elif action=='modify_customer':
        return modifycustomer(request)
    elif action=='del_customer':
        return deletecustomer(request)

    else:
        return JsonResponse({'ret':1,'msg':'不支持该类型http请求'})

def listcustomers(request):
    #返回一个queryset对象,包含的是所有的表记录
    qs=Customer.objects.values()
    #将queryset对象转化成list类型
    #否则不能被转化为json字符串
    retlist=list(qs)
    return JsonResponse({'ret':0,"retlist":retlist})

def addcustomer(request):
    info=request.params['data']
    #从请求消息中获取要添加客户的信息
    #并且插入到数据库中
    record=Customer.objects.create(name=info['name'],
                            phonenumber=info['phonenumber'],
                            address=info['address'])

    return JsonResponse({'ret':0,'id':record.id})

def modifycustomer(request):
    #从请求消息中获取修改客户的信息
    #找到该用户,并进行修改操作
    customerid=request.paras['id']
    newdata=request.params['newdata']

    try:
        #根据id 从数据库中找到对应的客户记录
        customer=Customer.objects.get(id=customerid)
    except Customer.DoesNotExist:
        return {
            'ret':1,
            'msg':f'id为{customerid}的客户不存在'
        }
    if 'name' in newdata:
        customer.name=newdata['name']
    if 'phonenumber' in newdata:
        customer.phonenumber=newdata['phonenumber']
    if 'address' in newdata:
        customer.address=newdata['address']

    #注意,一定要执行save才能将修改的信息保存到数据库
    customer.save()
    return JsonResponse({'ret':0})

def deletecustomer(request):
    customerid=request.params['id']
    try:
        #根据id 从数据库中找到对应记录
        customer=Customer.objects.get(id=customerid)
    except Customer.DoesNotExist:
        return {
            'ret':1,
            'msg':f'id为{customerid}的客户不存在'

        }
    #delete方法将该记录从数据库中删除
    customer.delete()
    return JsonResponse({'ret':0})